package me.shiqiang.im;

import com.tst.common.utils.DateUtils;
import me.shiqiang.im.service.StatisticsClient;
import me.shiqiang.im.statistics.LoginCount;
import me.shiqiang.im.vo.LoginStatisticsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by John on 2018/1/29
 */
//@Component
public class LoginStatisticsTask {

    @Autowired
    StringRedisTemplate redisTemplate;

    private static final Logger logger = LoggerFactory.getLogger(LoginStatisticsTask.class);

    private static boolean processFlag = false;

    @Value("${server.id}")
    private String id;

    @Autowired
    private StatisticsClient statisticsClient;

    /**
     * 每小时执行一次
     */
//    @Scheduled(cron = " 0 */1 * * * ?") //测试用，每分钟执行
//    @Scheduled(cron = "0 0 */1 * * ?")
    public void run() {
        try {
            if (processFlag) {
                logger.warn(String.format("[%s]上一次任务还在执行,本次跳过", this.getClass().getSimpleName()));
                return;
            }
            processFlag = true;

            process();
        } catch (Exception e) {
            logger.error("LoginStatisticsTask run error", e);
        } finally {
            processFlag = false;
        }
    }

    /**
     * IM登录人数统计task
     */
    private synchronized void process() {
        try {
            LoginStatisticsVo vo = new LoginStatisticsVo();
            String date = DateUtils.format(new Date(), new SimpleDateFormat("yyyy:MM:dd:HH").toPattern());
            vo.setDate(date);
            vo.setServerId(id);
            vo.setCount(LoginCount.getInstance().getMaxCount());
            statisticsClient.saveLoginStatistics(vo);
        } catch (Exception e) {
            logger.error("LoginStatisticsTask process error", e);
        }
    }
}
